package com.freestyle.nettychat.chat.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.freestyle.netty.easynetty.common.Utils;
import com.freestyle.nettychat.chat.CodeConsts;
import com.freestyle.nettychat.chat.dto.*;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by rocklee on 2022/2/6 12:15
 */
public class LogMessageDeserializer extends StdDeserializer<LogMessage> {

  public LogMessageDeserializer(Class<?> vc) {
    super(vc);
  }
  public LogMessageDeserializer(){
    this(null);
  }
  @Override
  public LogMessage deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);
    ChatMessageProperties properties= Utils.fromJson(node.get("properties").toString(), ChatMessageProperties.class);
    LogMessage logMessage=new LogMessage();
    logMessage.setProperties(properties);
    List<ChatMessage> data=new LinkedList<>();
    logMessage.setData(data);
    node.get("data").elements().forEachRemaining(n->{
       ChatMessage message=null;
       ChatMessageProperties properties1=Utils.fromJson(n.get("properties").toString(),ChatMessageProperties.class);
       try {
         String content=n.toString();
         switch (CodeConsts.MessageType.fromValue(properties1.getSClass())) {
           case text:
             message = Utils.fromJson(content, TextMessage.class);
             break;
           case attachment:
             message = Utils.fromJson(content, AttachmentMessage.class);
             break;
           default:
             message=Utils.fromJson(content,ChatMessage.class);
         }
         data.add(message);
       }
       catch (Exception e){
         e.printStackTrace();
       }
    });
    return logMessage;
  }
}
